package logic

import (
	"context"
	"errors"
	"registers/model/cache"
	"registers/model/mysql"
	"registers/pkg"

	"registers/registersrpc/internal/svc"
	"registers/registersrpc/registersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *LoginLogic) Login(in *registersrpc.LoginRequest) (*registersrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByAccounts(mysql.DB, in.Account)
	if err != nil {
		return nil, errors.New("该账号不存在")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码或者账号错误")
	}

	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()

	if in.CaptchaImage != result {
		return nil, errors.New("验证码错误 请重新输入")
	}

	results, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Account).Result()

	if in.SendSms != results {
		return nil, errors.New("短信验证码错误 请重新输入")
	}

	return &registersrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
